
module Pan
  
  require 'pp'
  require 'yaml'
  
  class SessionRegistry 
    @@session_file = "state.dump"
    
    def initialize 
      @lock = Mutex.new
      begin 
        DISABLED
        puts "loading sessions"
        load
      rescue Exception => e
        puts "ouch starting with empty registry {}"
        #puts "#{e.inspect}"
        #pp e.backtrace
        @items = {}
      end
    end 

    def new_session_key
      sprintf("%08x", rand(2**32)).upcase
    end
    
    def register(item, key=nil) 
      key = sprintf("%04x", @items.size).upcase if not key
      @lock.synchronize {
        @items[key] = item 
      }
      key
    end 
    
    def find(key) 
      purge_stale_sessions
      @lock.synchronize {
        @items[key]
      }
    end 
    
    def purge_stale_sessions
      @lock.synchronize {
        stale_keys = @items.keys().select{|key| @items[key].staleness > 60*15 }
        stale_keys.each do |key|
          @items.delete(key)
        end
      }
    end

    def size
      @items.size
    end

    ### YAML
    
    def save
      File.open(@@session_file,"w") { |fh| fh.write(YAML.dump(@items)) }
    end
    
    def load
      @items = YAML.load_file(@@session_file)
      @items.each {|key, val| 
        puts "calling init on: #{key}, #{val.inspect}"
        val.init()
      }
      puts "LOADED SESSIONS"
      puts "#"*80
      pp @items
      puts "#"*80
    end
    
    ### Marshal
    
    def msave
      File.open(@@session_file,"w") { |fh| Marshal.dump(@items,fh) }
    end
    
    def mload
      File.open(@@session_file) { |fh| 
        @items = Marshal.load(fh)
      }
      puts "LOADED SESSIONS"
      puts "#"*80
      pp @items
      puts "#"*80
    end
  end
end
